package com.sasis.webapp.action;

import java.util.Collection;
import java.util.Map;

import com.achievo.struts.ActionContext;
import com.sasis.model.CurrentUser;
import com.sasis.model.User;
import com.sasis.service.FunctionService;
import com.sasis.service.HandleTypeService;
import com.sasis.webapp.form.PermissionForm;

public class PermissionAction {
	
	private FunctionService functionService;
	
	private HandleTypeService handleTypeService;
	
	// IoC ------------

	public void setFunctionService(FunctionService functionService) {
		this.functionService = functionService;
	}

	public void setHandleTypeService(HandleTypeService handleTypeService) {
		this.handleTypeService = handleTypeService;
	}
	
	// Action ----------
	
	public String viewPermissionsTree(final PermissionForm permissionForm, final Map outMap) {
		try {
			Map applicationMap = ActionContext.getActionContext().getApplicationMap();
			Collection permissionsTree = (Collection)applicationMap.get("handlesTree");
			if (permissionsTree == null || permissionsTree.size() == 0) {
				permissionsTree = functionService.getHandlesTree();
				applicationMap.put("handlesTree", permissionsTree);
			}
			Collection handleTypes = (Collection)applicationMap.get("handleTypes");
			if (handleTypes == null || handleTypes.size() == 0) {
				handleTypes = handleTypeService.getHandleTypes();
				applicationMap.put("handleTypes", handleTypes);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return Forward.SUCCESS;
	}
	
	public String viewFunctionsTree(final PermissionForm permissionForm, final Map outMap) {
		try {
/*			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
			User user = (User)authentication.getPrincipal();
*/
			User user = CurrentUser.get(); 
			System.out.println("-----user" + user);
			Map sessionMap = ActionContext.getActionContext().getSessionMap();
			Collection functionsTree = (Collection)sessionMap.get("functionsTree");
			if (functionsTree == null || functionsTree.size() == 0) {
				functionsTree = functionService.getFunctionsTreeByUser(user.getId());
				sessionMap.put("functionsTree", functionsTree);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return Forward.SUCCESS;
	}

}
